<template>
	<view class="server-place">
		<map id='map' ref='map' :scale="scaleSize" v-bind:style="{height: mapH + 'px'}" style="width: 100%;"
			:latitude="latitude" :longitude="longitude" :controls='controls' :enable-poi="true"
			@regionchange='mapChange'></map>


		<cover-image v-bind:style="{left: controlsLeft + 'px', top: controlsTop + 'px'}" class="controls-location"
			:src="positionIcon"></cover-image>
		<!-- <cover-image class="chonghui-location" :src="myPositionIcon" @click="toMyLocation()"></cover-image> -->

		<!-- #ifndef APP-PLUS -->
		<!-- #endif -->

		<view class="map-tools">
			<view class="sousuodidian">
				<u-search v-model="citykeys" placeholder="搜索地点" :show-action="false" :disabled="true"
					@click="startSousuo()"></u-search>
			</view>

			<!--搜索列表-->
			<view class="scroll-x">
				<scroll-view class="uni-swiper-tab" scroll-y :style="'height:'+scrollH+'upx'">
					<view class="x-weizhi-list-wrap">
						<view class="lanjiazai" style="margin-top: 30rpx;" v-if="skeletonLoading">
							<view>
								<u-loading :show="skeletonLoading" color="#FFB930"></u-loading>
								<view class="tag" style="font-size: 24rpx;">加载中...</view>
							</view>
						</view>
						<view v-if="Loadingchaoshi" class="noData_box">
							<image src="/static/images/noData.png" mode="widthFix"></image>
							<view>网络好像出问题了~<span @click="shuaxin()">刷新一下</span></view>
						</view>
						<view v-else class="addresxuanze" :class="[morenidx == index ? 'xzbgcolor' : '']"
							v-for="(item,index) in poiss" :key="index" @click="OkSelect(item,index)">
							<view class="xiangxidizhi">
								<view>{{item.title}}</view>
								<view>{{item.address}}</view>
							</view>
							<view class="xuanzicon" v-if="morenidx == index">
								<u-icon name="checkmark-circle-fill" size="48" color="#f7904e"></u-icon>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>

			<view class="start-place">
				<view class="lijipay">
					<u-button type="info" shape="circle" :ripple="false" @click="submitAdress()">确认选择</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp()

	var QQMapWX = require('@/common/qqmap-wx-jssdk.min.js')
	var qqmapsdk = new QQMapWX({
		key: '7DZBZ-Q5BWK-23ZJ7-AOV3F-4VZBZ-NCFO3'
	})
	export default {
		props: {
			tipText: {
				type: String,
				default: '选择位置'
			},
			descText: {
				type: String,
				default: '使用当前定位或在地图上标记位置'
			},
			positionIcon: {
				type: String,
				default: '/static/position.png'
			},
			myPositionIcon: {
				type: String,
				default: '/static/8CjxSJ.png'
			}
		},
		data() {
			return {
				Loadingchaoshi: false,

				skeletonLoading: true,
				scrollH: 630,
				scaleSize: 17, //缩放级别
				mapH: 0, // 地图高度，可在initMapH()中设置高度
				mapW: 0, // 屏幕宽度
				longitude: 0, // 初始经度
				latitude: 0, // 初始纬度
				myAddress: '', // 初始地址信息
				addressObj: { // 地图选点信息
					longitude: '',
					latitude: '',
					address: '请选择地点'
				},

				// cover-image的默认 超出屏幕外 不然会有闪烁出现
				controlsLeft: 1000,
				controlsTop: 1000,
				controls: [], // 地图中心点图标, 可更换iconPath, 详情见官方文档关于map组件的介绍

				poiss: [],
				morenidx: 0,
				citykeys: ''

			};
		},
		onLoad() {
			let that = this

			that.initMapH()
			that.initPositionIcon()

			uni.$on('renewMap', (data) => {
				that.checkMap(data.data)
				that.upmapref(data.data)
			})

		},
		onShow() {
			let that = this
			that.JianCeNetwork()
		},
		methods: {
			//监测网络状态
			JianCeNetwork() {
				let that = this
				uni.getNetworkType({
					success: function(res) {
						//console.log(res.networkType);
						if (res.networkType == 'none') {
							that.Loadingchaoshi = true
							that.skeletonLoading = false
						} else {
							//that.Loadingchaoshi = true
							//当前有网络
							// #ifdef H5 || MP-WEIXIN
							that.H5getLocation()
							// #endif

							// #ifdef APP-PLUS
							that.AppgetLocation()
							// #endif
						}
					}
				});
			},
			//刷新重新定位
			shuaxin() {
				let that = this
				that.Loadingchaoshi = false
				that.skeletonLoading = true
				that.JianCeNetwork()
			},
			//选择周边位置
			OkSelect(data, idx) {
				let that = this
				that.morenidx = idx
				console.log('哈哈哈',data)
				that.addressObj = {
					longitude: data.location.lng,
					latitude: data.location.lat,
					address: {
						address: data.address,
						City: data.ad_info.city,
						poistitle: data.title,
						province: data.ad_info.province
					}
				}
			},

			// 初始化地图中心位置的定位图片
			initPositionIcon() {
				setTimeout(() => {
					// H5 微信小程序 使用<cover-image>
					// #ifndef APP-PLUS
					this.controlsLeft = this.mapW / 2 - 20
					this.controlsTop = this.mapH / 2
					// #endif

					// App使用map的controls
					// #ifdef APP-PLUS
					var controls = {
						id: '1',
						iconPath: this.positionIcon,
						position: {
							left: this.mapW / 2 - 10,
							top: this.mapH / 2 - 100,
							width: 30,
							height: 30,
						},
						clickable: false
					}
					this.controls.push(controls)
					////console.log(this.controls, '==========');
					// #endif
				}, 100)
			},
			//APP查询现在的位置
			AppgetLocation() {
				let this_ = this

				uni.getLocation({
					type: 'gcj02',

					//安卓打包开启 IOS打包注释掉  因为IOS上获取很慢位置问题
					//highAccuracyExpireTime: "3000",
					//isHighAccuracy: true,

					success: function(res) {
						this_.initMap(res)
					},
					fail: function(e) {
						alert(JSON.stringify(e))
						uni.showToast({
							icon: 'none',
							title: '获取地址失败, 请检查是否开启定位权限~~'
						})
					}
				})
			},
			// H5查询现在的位置
			H5getLocation() {
				let this_ = this
				let weidu = uni.getStorageSync('lat')
				let jingdu = uni.getStorageSync('lng')

				if (!weidu || !jingdu) {
					//console.log('本地没有经纬度')
					uni.getLocation({
						type: 'gcj02',
						highAccuracyExpireTime: 3000, // 高精度定位超时时间(ms)
						isHighAccuracy: true, // 开启高精度定位
						success: function(res) {
							this_.initMap(res)
						},
						fail: function(e) {
							alert(JSON.stringify(e))
							this_.skeletonLoading = false
							this_.Loadingchaoshi = true
							uni.showToast({
								icon: 'none',
								title: '获取地址失败, 请检查是否开启定位权限~~'
							})
						}
					})
				} else {
					//console.log('本地有经纬度')
					let ress = {
						latitude: weidu,
						longitude: jingdu
					}
					this_.initMap(ress)
				}


			},

			// 初始化我的位置
			async initMap(res) {
				let that = this
				that.longitude = res.longitude;
				that.latitude = res.latitude;
				that.myAddress = await that.getAddressName(res);

				that.addressObj = {
					longitude: res.longitude,
					latitude: res.latitude,
					address: that.myAddress
				}

				//在获取个周边位置信息
				this.morenidx = 0
				let poiSs = await that.getAddressName(res);
				that.poiss = poiSs.ispoiss
				//that.skeletonLoading = false

				uni.createMapContext("map", this)
			.moveToLocation({ //moveToLocation将地图中心移动到当前定位点，需要配合map组件的show-location使用
					latitude: this.latitude,
					longitude: this.longitude
				});

			},

			// 地图选择位置后 查询地点名称
			async checkMap(res) {
				this.addressObj = Object.assign({}, this.addressObj, {
					longitude: res.longitude,
					latitude: res.latitude,
					address: await this.getAddressName(res)
				})
				//在获取个周边位置信息
				this.morenidx = 0
				let poiSs = await this.getAddressName(res);
				this.poiss = poiSs.ispoiss
				//this.skeletonLoading = false
			},

			//搜索选择回来顺便把地图更新一下
			upmapref(item) {
				uni.createMapContext("map", this).moveToLocation({ //moveToLocation将地图中心移动到当前定位点，需要配合map组件的show-location使用
					latitude: item.latitude,
					longitude: item.longitude
				});
			},

			// 监听地图位置变化
			mapChange(e) {
				let that = this

				clearTimeout(this.timer)
				that.timer = setTimeout(() => {
					if (e.type == 'regionchange' || e.type == 'end') {
						that.mapCtx = uni.createMapContext('map', this)
						that.mapCtx.getCenterLocation({
							success: res => {
								this.checkMap(res)
								that.scaleSize = 17
							},
							fail: err => {
								//console.log(err);
							}
						})
					}
				}, 200)
			},
			// 查询地图中心点的名称
			getAddressName(addressObj) {
				let that = this
				return new Promise((res) => {
					// #ifdef APP-PLUS
					qqmapsdk.reverseGeocoder({
						location: {
							latitude: addressObj.latitude,
							longitude: addressObj.longitude
						},
						get_poi: 1,
						poi_options: "page_size=1;page_index=1",
						output: 'jsonp',
						success: (e) => {
							//console.log('APP-端当前城市信息', e.result)
							res({
								address: e.result.formatted_addresses.recommend,
								City: e.result.ad_info.city,
								ispoiss: e.result.pois
							});
							that.skeletonLoading = false
						},
						fail: err => {
							res(err);
							that.skeletonLoading = false
							that.Loadingchaoshi = true
						}
					})
					// #endif

					// #ifdef H5
					this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1/', {
						location: addressObj.latitude + ',' + addressObj.longitude,
						key: '7DZBZ-Q5BWK-23ZJ7-AOV3F-4VZBZ-NCFO3',
						get_poi: 1,
						poi_options: 'policy=2',
						output: 'jsonp'
					}).then(Nres => {
						//console.log('H5-端当前城市信息', Nres)

						if (Nres.status === 0) {
							res({
								address: Nres.result.pois[0].address,
								City: Nres.result.pois[0].ad_info.city,
								ispoiss: Nres.result.pois,
								poistitle: Nres.result.pois[0].title
							});
							that.skeletonLoading = false

						} else {
							that.skeletonLoading = false
							that.Loadingchaoshi = true
						}

					}).catch(err => {
						that.skeletonLoading = false
						that.Loadingchaoshi = true
						res(err)
					})

					// #endif

					// #ifdef MP-WEIXIN
					////console.log(addressObj, '======================');
					qqmapsdk.reverseGeocoder({
						location: {
							latitude: addressObj.latitude,
							longitude: addressObj.longitude
						},
						get_poi: 1,
						poi_options: "page_size=1;page_index=1",
						output: 'jsonp',
						success: (e) => {
							//console.log('小程序-端当前城市信息', e)
							res({
								address: e.result.formatted_addresses.recommend,
								City: e.result.ad_info.city,
								ispoiss: e.result.pois,
								poistitle: e.result.pois[0].title
							});
							that.skeletonLoading = false
						},
						fail: err => {
							res(err);
							that.skeletonLoading = false
							that.Loadingchaoshi = true
						}
					})
					// #endif


				})

			},
			// 计算地图的高度
			initMapH() {
				// #ifdef APP-PLUS
				this.mapW = uni.getSystemInfoSync().windowWidth
				this.mapH = uni.getSystemInfoSync().windowHeight - 430;
				// #endif

				// #ifndef APP-PLUS
				this.mapW = uni.getSystemInfoSync().windowWidth
				this.mapH = uni.getSystemInfoSync().windowHeight - 440;
				// #endif

				// #ifdef MP-WEIXIN
				this.mapW = uni.getSystemInfoSync().windowWidth
				this.mapH = uni.getSystemInfoSync().windowHeight - 440;
				// #endif
			},
			// 移动到我的位置
			toMyLocation() {
				// #ifdef H5 || MP-WEIXIN
				this.H5getLocation()
				// #endif

				// #ifdef APP-PLUS
				this.AppgetLocation()
				// #endif
			},
			// 提交
			submitAdress() {
				//this.controls = []
				setTimeout(() => {
					this.updateAddress(this.addressObj)
				}, 100)
			},
			updateAddress(addressObj) {

				let SelectedCity = addressObj.address.City
				let presentCity = uni.getStorageSync('CityName')

				console.log('啊啊啊', addressObj)
				//判断当前定位城市如果不等于选择的城市 就不能切换位置 不能跨城市选择
				if (presentCity != SelectedCity) {
					uni.showModal({
						title: '提示',
						showCancel: false,
						content: '不能切换到定位之外的其他城市',
						confirmText: '我知道了',
						success: function(res) {
							if (res.confirm) {
								//console.log('用户点击确定');
							} else if (res.cancel) {
								//console.log('用户点击取消');
							}
						}
					});
				} else {

					//原先的方式
					/*uni.setStorageSync('lat', addressObj.latitude);
					uni.setStorageSync('lng', addressObj.longitude);
					uni.setStorageSync('address', addressObj.address.poistitle);
					uni.$emit('Getlist', {
						id: 1,
					});*/

					uni.$emit('GetAddressData', {
						data: addressObj,
					});
					uni.navigateBack()

				}
			},
			startSousuo() {
				let that = this
				uni.navigateTo({
					url: '/subpackageB/pages/Selectlocation/Searchlocation?lat=' + that.latitude + '&log=' + that.longitude,
					animationType: 'pop-in'
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.quyu333 {
		color: #ff682e;
		margin-left: 10rpx;
	}

	.noData_box {
		margin-top: 0;
		text-align: center;
		color: #999;

		image {
			width: 280rpx;
		}

		span {
			color: #FE9400;
		}

		.lijipay {
			width: 30%;
			position: relative;
			margin: 0 auto;

			.u-size-default {
				height: 70rpx !important;
				line-height: 70rpx !important;
			}
		}
	}


	.chonghui-location {
		height: 36px;
		width: 36px;
		position: absolute;
		top: 33.5%;
		left: 20rpx;
		border-radius: 20rpx;
	}

	.lijipay {
		margin: 0 auto 0;
		width: 100%;

		.u-size-default {
			height: 80rpx !important;
			line-height: 80rpx !important;
			background-image: linear-gradient(to right, #FE9400, #FF3D22) !important;
			color: #fff;
		}
	}

	.sousuodidian {
		background-color: #ffffff;
		width: 100%;
		padding: 20rpx;
		position: relative;
		z-index: 5;
		box-shadow: 0 0 13px 0px rgba(0, 0, 0, 0.12);
		-webkit-box-shadow: 0 0 13px 0px rgba(0, 0, 0, 0.12);
		-moz-box-shadow: 0 0 13px 0px rgba(0, 0, 0, 0.12);
	}

	.controls-location {
		height: 46px;
		width: 46px;
		position: absolute;
	}

	.server-place {
		//position: fixed;
		left: 0;
		top: 0;
		height: 100vh;
		width: 100%;
		background: #ffffff;

		.map-tools {
			.my-location {
				width: 90%;
				margin: 0 auto;
				height: 120rpx;
				box-shadow: 0px 3px 20px rgba(0, 0, 0, 0.2);
				background: #fff;
				border-radius: 20rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				overflow: hidden;

				.left {
					background: #ffe62e;
					// flex: 20%;
					width: 120rpx;
					height: 100%;
				}

				.right {
					margin-left: 20rpx;
					color: #111;
					display: flex;
					justify-content: center;
					align-items: flex-start;
					flex-direction: column;

					.title {
						font-size: 28rpx;
						font-weight: bold;
					}

					.text {
						font-size: 26rpx;
						width: 500rpx;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
						color: #909090;
						margin-top: 10rpx;
					}
				}
			}

			.start-place {
				width: 100%;
				margin: 0 auto;
				background: #fff;
				padding: 30rpx 20rpx;
				position: fixed;
				left: 0;
				right: 0;
				bottom: 0;
				box-shadow: 0 0 13px 0px rgba(0, 0, 0, 0.12);
				-webkit-box-shadow: 0 0 13px 0px rgba(0, 0, 0, 0.12);
				-moz-box-shadow: 0 0 13px 0px rgba(0, 0, 0, 0.12);

				.place {
					display: flex;
					justify-content: flex-start;
					align-items: center;

					.title {
						font-size: 28rpx;
						font-weight: bold;
						color: #111;
					}

					.text {
						font-size: 28rpx;
						color: #ff682e;
						font-weight: bold;
						width: 450rpx;
						display: inline-block;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}

				.tip {
					font-size: 22rpx;
					color: #666;
					margin-top: 15rpx;
				}

				.sure {
					margin-top: 15rpx;
					color: #333;
					background: #ffe62e;
					font-weight: blod;
					font-size: 32rpx;
					font-weight: 600;
				}

			}
		}
	}

	.x-weizhi-list-wrap {
		padding: 0 0 80rpx 0;

		.addresxuanze {
			background-color: #ffffff;
			padding: 30rpx 20rpx;
			position: relative;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 1px solid #f7f7f7;

			.dqwez {
				color: #333333;

				view:nth-child(1) {
					margin-bottom: 10rpx;
					font-weight: bold;
				}

				view:nth-child(2) {
					display: flex;
					align-items: center;
					color: #999999;
					word-break: break-all;
					display: -webkit-box;
					-webkit-line-clamp: 1;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
			}

			.xiangxidizhi {
				view:nth-child(1) {
					margin-bottom: 10rpx;
					font-weight: bold;
				}

				view:nth-child(2) {
					display: flex;
					align-items: center;
					color: #999999;
					word-break: break-all;
					display: -webkit-box;
					-webkit-line-clamp: 1;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
			}

			.xuanzicon {
				//position: absolute;
				//right: 12rpx;
				//top: 16rpx;
			}
		}

		.addresxuanze:last-child {
			border: none;
		}
	}
</style>